<template>
  <a-layout-header
    class="fixed top-0 left-0 z-[999] !flex !h-full !w-[60px] flex-col items-center justify-between border-r border-[rgba(228,228,235,0.8)] !bg-[#f7f9fc] !px-0 !py-8 !leading-[1.5]"
  >
    <!-- logo -->
    <router-link to="/">
      <div class="text-center">
        <img
          src="@/assets/images/logo.png"
          alt="logo"
          class="mx-auto h-7"
        />
        <div class="mt-0.5 font-['抖音美好体'] text-sm text-gray-800">星绘</div>
      </div>
    </router-link>

    <!-- 菜单栏 -->
    <a-menu
      v-model:selectedKeys="current"
      mode="vertical"
      :items="items"
      @click="menuClickHandle"
      class="!-mt-[120px] !border-0 !bg-transparent"
    />

    <!-- 其它 -->
    <div class="flex flex-col items-center justify-center">
      <!-- 登录按钮 -->
      <router-link
        to="user/login"
        v-if="userStore.loginUser.userName === '未登录'"
      >
        <div
          class="cursor-pointer rounded-md bg-[#303540] px-1.5 py-0.5 text-xs font-light text-white"
          title="登录"
        >
          登录
        </div>
      </router-link>

      <!-- 登录后状态 -->
      <div
        class="group relative cursor-pointer hover:opacity-100"
        v-else
      >
        <a-avatar
          :size="34"
          shape="square"
          class="!bg-white"
          :src="
            loginUser.userAvatar && loginUser.userAvatar.length > 0
              ? loginUser.userAvatar
              : 'https://www.antdv.com/assets/logo.1ef800a8.svg'
          "
        />

        <!-- 弹窗 -->
        <div
          class="invisible absolute bottom-0 left-[40px] w-[242px] origin-bottom-left scale-0 rounded-xl border border-gray-200 bg-white p-2 opacity-0 shadow-[0_4px_40px_#8087af40] transition-all duration-300 group-hover:visible group-hover:scale-100 group-hover:opacity-100"
        >
          <div class="flex items-center rounded-[9px] bg-[#f6f6f6] p-2">
            <a-avatar
              :size="38"
              shape="square"
              class="!bg-white"
              :src="
                loginUser.userAvatar && loginUser.userAvatar.length > 0
                  ? loginUser.userAvatar
                  : 'https://www.antdv.com/assets/logo.1ef800a8.svg'
              "
            />
            <div class="ml-3.5">
              <div class="text-sm font-medium">{{ loginUser.userAccount }}</div>
              <div class="text-xs text-gray-500">ID:{{ loginUser.id }}</div>
            </div>
          </div>
          <div class="mt-2.5 grid grid-cols-3 gap-x-1 gap-y-2">
            <div
              class="flex flex-col items-center justify-center rounded-md p-[8px_5px] text-center transition-all duration-300"
            >
              <Icon
                icon="mdi:help-circle"
                class="text-base text-gray-800"
              />
              <div class="mt-[5px] text-[12px] text-gray-500">帮助文档</div>
            </div>
            <div
              class="flex flex-col items-center justify-center rounded-md p-[8px_5px] text-center transition-all duration-300"
              @click="router.push('/user/policy')"
            >
              <Icon
                icon="mdi:shield-lock"
                class="text-base text-gray-800"
              />
              <div class="mt-[5px] text-[12px] text-gray-500">隐私政策</div>
            </div>
            <div
              class="flex flex-col items-center justify-center rounded-md p-[8px_5px] text-center transition-all duration-300"
              @click="router.push('/user/agreement')"
            >
              <Icon
                icon="mdi:file-document"
                class="text-base text-gray-800"
              />
              <div class="mt-[5px] text-[12px] text-gray-500">用户协议</div>
            </div>
            <div
              class="flex flex-col items-center justify-center rounded-md p-[8px_5px] text-center transition-all duration-300"
            >
              <Icon
                icon="mdi:gift"
                class="text-[15px] text-gray-800"
              />
              <div class="mt-[7px] text-[12px] text-gray-500">权益中心</div>
            </div>
            <div
              class="flex flex-col items-center justify-center rounded-md p-[8px_5px] text-center transition-all duration-300"
              @click="handleEditProfile"
            >
              <Icon
                icon="mdi:account-edit"
                class="text-[22px] text-gray-800"
              />
              <div class="mt-[2px] text-[12px] text-gray-500">修改资料</div>
            </div>
            <div
              class="flex flex-col items-center justify-center rounded-md p-[8px_5px] text-center transition-all duration-300"
              @click="userLogoutHandle"
            >
              <Icon
                icon="mdi:logout"
                class="text-[17px] text-red-500"
              />
              <div class="mt-[5px] text-[12px] text-red-500">退出登录</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-layout-header>
</template>

<script lang="ts" setup>
import { h, ref, computed, inject } from 'vue';
import { useRouter } from 'vue-router';
import type { MenuProps } from 'ant-design-vue';
import { Icon } from '@iconify/vue';
import { useUserStore } from '@/stores/user';
import { userLogout } from '@/api/userController';
import { message } from 'ant-design-vue';

// 路由
const router = useRouter();
// 用户store
const userStore = useUserStore();
// 直接使用 store 的响应式引用，保持响应性
const loginUser = computed(() => userStore.loginUser);

// 注入全局用户信息弹窗方法
const showUserInfoModal = inject<(userData?: API.UserVO) => void>('showUserInfoModal');
// 当前页面高亮路径
const current = ref<string[]>(['/']);

// 菜单项图标配置 - 默认和选中状态的图标
const menuIcons = {
  '/': {
    default: 'material-symbols-light:home-app-logo-outline',
    active: 'material-symbols-light:home-app-logo'
  },
  '/document': {
    default: 'material-symbols-light:edit-document-outline',
    active: 'material-symbols-light:edit-document'
  },
  '/admin/user-manage': {
    default: 'material-symbols-light:account-box-outline',
    active: 'material-symbols-light:account-box'
  }
};

// 菜单项 - 根据用户角色动态显示
const items = computed<MenuProps['items']>(() => {
  // 创建图标渲染函数
  const createIcon = (key: string) => {
    return () => {
      const isSelected = current.value.includes(key);
      const iconKey = isSelected ? 'active' : 'default';
      return h(Icon, { icon: menuIcons[key as keyof typeof menuIcons][iconKey] });
    };
  };

  const baseItems: MenuProps['items'] = [
    {
      key: '/',
      icon: createIcon('/'),
      label: '首页',
      title: '首页'
    },
    {
      key: '/document',
      icon: createIcon('/document'),
      label: '文档',
      title: '文档'
    }
  ];

  // 只有管理员才能看到用户管理菜单
  if (userStore.loginUser.userRole === 'admin') {
    baseItems.push({
      key: '/admin/user-manage',
      icon: createIcon('/admin/user-manage'),
      label: '用户',
      title: '用户管理'
    });
  }

  return baseItems;
});
// 菜单点击事件
const menuClickHandle: MenuProps['onClick'] = (e) => {
  const path = e.key as string;
  router.push(path);
};

// 后置钩子：路由跳转后，设置当前页面高亮
router.afterEach((to) => {
  current.value = [to.path];
});

/**
 * 编辑用户资料
 */
const handleEditProfile = () => {
  // 打开用户信息编辑弹窗，传入当前登录用户信息
  if (showUserInfoModal) {
    showUserInfoModal(loginUser.value as API.UserVO);
  }
};

/**
 * 用户退出登录
 */
const userLogoutHandle = async () => {
  try {
    const res = await userLogout();
    if (res.data?.code === 0) {
      userStore.setLoginUser({
        userName: '未登录'
      });
      message.success('退出登录成功');
      router.push('/user/login');
    } else {
      message.error(res.data?.message ?? '退出登录失败');
    }
  } catch (error) {
    console.error(error);
  }
};
</script>

<style lang="scss" scoped>
/* 清除 a-menu 默认样式 */
:deep(.ant-menu-item) {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: auto;
  height: auto;
  line-height: 1.5;
  margin: 0px;
  padding: 0px;
  border: 0px;
  font-size: 12px;
  margin-bottom: 34px;
  background: transparent !important;

  &.ant-menu-item-selected {
    background: none;

    .ant-menu-item-icon {
      color: inherit;
    }
  }

  &:last-child {
    margin-bottom: 0px;
  }

  .ant-menu-item-icon {
    min-width: auto;
    font-size: 26px;
    margin-bottom: 1px;
    color: #333;
  }

  .ant-menu-title-content {
    margin: 0px !important;
  }

  &:hover {
    background: none;
  }

  &:nth-child(1) {
    .ant-menu-item-icon {
      font-size: 28px;
    }
  }
}
</style>
